<!--
 * @Author: sxb
 * @Email: sxb@mail.com
 * @Date: 2020-06-19 15:01:42
 * @Descripttion: 
--> 
<template>
  <div class="app-container">
    <!--工具栏-->
    <el-form :inline="true" :model="query" class="demo-form-inline">
      <el-form-item label="部门名称">
        <el-input v-model="query.name" placeholder="请输入部门名称"></el-input>
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="query.enabled" size="small" placeholder="全部" class="filter-item" style="width: 90px">
          <el-option v-for="item in enabledTypeOptions" :key="item.key" :label="item.display_name" :value="item.key" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="mini" @click="getDepts">搜 索</el-button>
        <el-button size="mini" @click="clear">清 除</el-button>
      </el-form-item>
    </el-form>
    <el-row>
      <el-col>
        <el-button class="margin—buttom-18" size="mini" type="primary" icon="el-icon-plus" @click="addDepartment">
          新增
        </el-button>
        <el-button class="margin—buttom-18" size="mini" type="success" icon="el-icon-edit" :disabled="checkedList.length!==1" @click="editDepartment">
          修改
        </el-button>
        <el-button class="margin—buttom-18" size="mini" type="danger" icon="el-icon-delete" :disabled="checkedList.length==0" @click="doDelete">
          删除
        </el-button>
      </el-col>
    </el-row> 
    <!--表单组件-->
    <el-dialog :visible.sync="dialogFormVisible1" :title="dialogTitle" width="500px">
      <el-form ref="form" inline :model="form" :rules="rules" size="small" label-width="80px">
        <el-form-item label="部门名称" prop="name">
          <el-input v-model="form.name" style="width: 370px;" />
        </el-form-item>
        <el-form-item label="部门排序" prop="deptSort">
          <el-input-number
            v-model.number="form.deptSort"
            :min="0"
            :max="999"
            controls-position="right"
            style="width: 370px;"
          />
        </el-form-item>
        <el-form-item label="顶级部门">
          <el-radio-group v-model="form.isTop" style="width: 140px">
            <el-radio label="1">是</el-radio>
            <el-radio label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="状态">        
          <el-radio v-for="item in dept_status" :key="item.value" v-model="form.enabled" :label="item.value">{{ item.label }}</el-radio>
        </el-form-item>
        <el-form-item v-if="form.isTop === '0'" style="margin-bottom: 0;" label="上级部门" prop="pid">
          <!-- <treeselect v-model="form.pid" :load-options="loadDepts" :options="depts" style="width: 370px;" placeholder="选择上级类目" /> -->
          <el-select v-model="form.pid" placeholder="请选择" style="width: 370px;">
            <el-option
              v-for="item in depts"
              :key="item.id"
              :label="item.label"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="text" @click="dialogFormVisible1 = false">取消</el-button>
        <el-button type="primary"  @click="submitDepartment('form')">确认</el-button>
      </div>
    </el-dialog>
    <!--表格渲染-->
    <el-table :data="tableData1" style="width: 100%" row-key="id" lazy :load="load"
    :tree-props="{children: 'children', hasChildren: 'hasChildren'}" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column prop="name" label="名称" width="180">
      </el-table-column>
      <el-table-column prop="deptSort" label="排序" width="180">
      </el-table-column>
      <el-table-column prop="enabled" label="状态" align="center">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.enabled"
            :disabled="scope.row.id === 1"
            active-color="#409EFF"
            inactive-color="#F56C6C"
            @change="changeEnabled(scope.row, scope.row.enabled,)"
          />
        </template>
      </el-table-column>
        <el-table-column prop="createTime" width="135" label="创建日期">
          <template slot-scope="scope">
            <span>{{ scope.row.createTime }}</span>
          </template>
        </el-table-column>
      <el-table-column label="操作" width="130px" align="center" fixed="right">
        <template slot-scope="scope">
          <udOperation :data="scope.row" v-on:getDepts="getDepts" v-on:bindDepartment="bindDepartment" />
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>
<script>
import udOperation from "./module/ud.operation";
import { separateObj } from '@/utils/index'
import treeselect, {LOAD_CHILDREN_OPTIONS} from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { getDepts, add, del, edit } from '@/api/system/department'

export default {
  components: {
    treeselect,
    udOperation
  },
  data(){
    return{
      checkedList: [],
      depts: [],
      enabledTypeOptions: [
        { key: 'true', display_name: '正常' },
        { key: 'false', display_name: '禁用' }
      ],
      dept_status:[
        { value: 'true', label: '启用' },
        { value: 'false', label: '停用' }
      ],
      query: {
        name: '',
        enabled: ''
      },
      dialogTitle: '新增部门',
      dialogFormVisible1: false,
      form:{
        id: null, 
        name: null, 
        isTop: '1', 
        subCount: 0, 
        pid: null, 
        deptSort: 999, 
        enabled: 'true'
      },
      rules: {
        name: [
          { required: true, message: '请输入名称', trigger: 'blur' }
        ],
        deptSort: [
          { required: true, message: '请输入序号', trigger: 'blur', type: 'number' }
        ]
      },
      tableData1: []
    }
  },
  created() {
    this.getDepts()
  },
  methods: {
    clear(){
      this.query = { name: '', enabled: '' }
    },
    load(tree, treeNode, resolve) {
      const params = { pid: tree.id }
      setTimeout(() => {
        getDepts(params).then(res => {
          console.log(res.content)
          resolve(res.content)
        })
      }, 100)
    },
    getDepts() {
      getDepts(this.query).then(res => {
        this.tableData1 = res.content
        this.depts = res.content.map(function(obj) {
          if (obj.hasChildren) {
            obj.children = null
          }
          return obj
        })
      })
    },
    // 获取弹窗内部门数据
    loadDepts({ action, parentNode, callback }) {
      let self= this
      if (action === LOAD_CHILDREN_OPTIONS) {
          console.log('getDepts')
        getDepts({ enabled: true, pid: parentNode.id }).then(res => {
          console.log(res)
          parentNode.children = res.content.map(function(obj) {
            if (obj.hasChildren) {
              obj.children = null
            }
            console.log(self.depts)
            return obj
          })
          setTimeout(() => {
            callback()
          }, 100)
        })
      }
    },
    // 改变状态
    changeEnabled(data, val) {
      let status = {"true":"启用","false":"停用"}
      this.$confirm('此操作将 "' + status[val] + '" ' + data.name + '部门, 是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        edit(data).then(res => {
          this.$message({
            type: 'success',
            message: '执行成功!'
          });
        }).catch(err => {
          data.enabled = !data.enabled
          //console.log(err.response.data.message)
        })
      }).catch(() => {
        data.enabled = !data.enabled
      })
    },
    addDepartment(){
      if(this.form.name !== null){
        this.form = {
          id: null, 
          name: null, 
          isTop: '1', 
          subCount: 0, 
          pid: null, 
          deptSort: 999, 
          enabled: 'true'
        },
        console.log(this.form)
        this.$refs['form'].resetFields();
      }
      this.dialogFormVisible1 = true;
      this.getDepts()
    },
    editDepartment(){     
      this.form = separateObj(this.checkedList[0])
      let form = this.form      
      // if (form.pid !== null) {
      //   form.isTop = '0'
      // } else if (form.id !== null) {
      //   form.isTop = '1'
      // }
      form.isTop = form.topLevel ? '1' : '0'
      form.enabled = `${form.enabled}`
      this.dialogFormVisible1 = true;
    },
    bindDepartment(data){     
      this.form = separateObj(data)
      let form = this.form      
      form.isTop = form.topLevel ? '1' : '0'
      form.enabled = `${form.enabled}`
      this.dialogFormVisible1 = true;
    },
    submitDepartment(formName){
      let self = this
      let form = this.form
      let api = add
      if(form !== undefined && form.id !== null){
        api = edit
      } 
      this.$refs[formName].validate((valid) => {
          if (valid) {
            console.log(JSON.stringify(form))
            api(form).then(res => {
              this.$message({
                type: 'success',
                message: '执行成功!'
              });
              this.dialogFormVisible1 = false
              //location.reload()     
              //this.$refs[formName].resetFields();         
              this.getDepts()
            })
            .catch(error => {
              console.log(error)
            })
          } else {
            console.log('error submit!!');
            return false;
          }
        });
    },
    handleSelectionChange(val) {
      this.checkedList = val;
    },
    doDelete(){
      let delList = [];
      this.checkedList.forEach(item=>{
        return delList.push(item.id)
      })
      this.$confirm(`确认删除选中的${delList.length}条数据?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        del(delList)
          .then(res => {
            this.getDepts();
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
          })
          .catch(error => {
            this.$message({
              type: 'info',
              message: 'error'
            });  
          });
      }).catch();
    }
  }
}
</script>
<style scoped>
.margin—buttom-18{
  margin-bottom: 18px !important
}
</style>
<style rel="stylesheet/scss" lang="scss" scoped>
  /deep/ .vue-treeselect__control, /deep/ .vue-treeselect__placeholder, /deep/ .vue-treeselect__single-value {
    height: 30px;
    line-height: 30px;
  }
</style>
<style rel="stylesheet/scss" lang="scss" scoped>
  /deep/ .el-input-number .el-input__inner {
    text-align: left;
  }
</style>